package com.itttq.gshop.h5.cmpt;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * 阿里大于发送短信
 * @author butterfly
 */
@Component
public class SMSAlidayu {
	private Logger logger = LoggerFactory.getLogger(SMSAlidayu.class);
	//产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    
	@Value("${sms.alidayu.serverUrl}")
	private String URL;
	@Value("${sms.alidayu.appKey}")
	private String accessKeyId;
	@Value("${sms.alidayu.signature}")
	private String signature;
	@Value("${sms.alidayu.appSecret}")
	private String accessKeySecret;
	@Value("${sms.alidayu.productName}")
	private String productName;
	@Value("${sms.alidayu.tmpl.regCode}")
	private String regCode;
//	@Value("${sms.alidayu.tmpl.noticLoanCode}")
//	private String noticLoanCode;
	@Value("${sms.alidayu.tmpl.forgetpwdCode}")
	private String forgetpwdCode;
	/**
	 * 下发短信
	 * @param content		参数内容，json格式。
	 * @param phone			下发手机号
	 * @param tmplCode	模板编号
	 * @param extend			透传
	 * @return
	 */
	public boolean sendSms(String content, String phone, String tmplCode, String outId) {
		logger.info("阿里大于 - 下发开始:{},内容={},编码={}",phone, content, tmplCode);
		boolean sended = false;
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        try {
	        //初始化acsClient,暂不支持region化
	        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
	        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	        IAcsClient acsClient = new DefaultAcsClient(profile);
	
	        //组装请求对象-具体描述见控制台-文档部分内容
	        SendSmsRequest request = new SendSmsRequest();
	        //必填:待发送手机号
	        request.setPhoneNumbers(phone);
	        //必填:短信签名-可在短信控制台中找到
	        request.setSignName(signature);
	        //必填:短信模板-可在短信控制台中找到
	        request.setTemplateCode(tmplCode);
	        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
	        if(StringUtils.isNotBlank(content)) request.setTemplateParam(content);
	
	        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
	        //request.setSmsUpExtendCode("90997");
	
	        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
	        request.setOutId(outId);
        
	        SendSmsResponse response = acsClient.getAcsResponse(request);
			if (null != response) {
				if (null != response.getCode() && response.getCode().equalsIgnoreCase("OK")) {
					logger.info("下发成功, phone={}, RequestId={}", phone, response.getRequestId());
					sended = true;
				} else {
					logger.info("下发失败, phone={}, code={}, msg={}", phone, response.getCode(), response.getMessage());
				}
			} else {
				logger.warn("阿里大于 -  下发失败, {}", phone);
			}
		} catch (Exception e) {
			logger.error("阿里大于 -  下发异常,"+phone+" - errorMsg:", e);
		}
		return sended;
	}
	
	/**
	 * 发送注册验证码
	 * @param phone
	 * @return
	 */
	public boolean sendRegCode(String phone, String code) {
		JSONObject json = new JSONObject();
		json.put("code", code);
		return sendSms(json.toString(), phone, regCode, phone);
	}
	
	/**
	 * 发送忘记密码验证码。模板为：验证码${code}，您正在尝试修改${product}登录密码，请妥善保管账户信息。
	 * @param phone
	 * @return
	 */
	public boolean sendForgetpwdCode(String phone, String code) {
		JSONObject json = new JSONObject();
		json.put("code", code);
		return sendSms(json.toString(), phone, forgetpwdCode, phone);
	}
	
//	/**
//	 * 批量下发短信
//	 * @param signature		签名，必须是在阿里大于审核通过的
//	 * @param content		参数内容，json格式。
//	 * @param phone			下发手机号
//	 * @param tmplCode	模板编号
//	 * @param extend			透传
//	 * @return
//	 */
//	public boolean sendSmsBatch(String content, String phone) {
//		return sendSms(null, phone, noticLoanCode, phone.length() > 60 ? phone.substring(0, 60) : phone );
//	}
	
	public static void main(String[] args) {
		JSONObject json = new JSONObject();
		json.put("customer", "gxg");
		SMSAlidayu dayu = new SMSAlidayu();
		dayu.signature = "信如金";
		dayu.forgetpwdCode = "SMS_86895297";
		dayu.URL = "http://gw.api.taobao.com/router/rest";
		dayu.accessKeyId = "LTAIXY1IqvOPVA2s";
		dayu.accessKeySecret = "4mOjufq9GpQwKukUKYZxTkY5C8zrUK";
		System.out.println(
				dayu.sendForgetpwdCode("15086892315", "1345")
//				dayu.sendSms(null, "15086892315,18302368788", "SMS_88060010", "15086892315,18302368788")
				);
	}
}
